package gob.cgr.sgrh.ejb.session;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;


import gob.cgr.sgrh.ejb.local.GenericDAO;
/**
 * @author wcvaler
 * @version  1.0
 * @see  interfaz GenericDAO
 * 
 * Implementacion de la interfaz GenericDAO
 */


public abstract class GenericSessionImpl <T extends Serializable, PK extends Serializable> implements GenericDAO<T,PK>{
	
	
	@PersistenceContext(unitName="EJBRH")
	private EntityManager em;
	
	private Class<T> persistentClass;
	
	public EntityManager getEm() {
		return em;
	}
	public void setEm(EntityManager em) {
		this.em = em;
	}
	@Override
	public T obtener(Serializable id) {
		
		return em.find(persistentClass, id);
	}
	@Override
	public void registrar(T object) {
		// TODO Auto-generated method stub
		System.out.println("El persitence Unit al actualizar es :::"+em+"**********************");
		em.persist(object);
		System.out.println("yuppiiiiii");
	}
	@Override
	public void eliminar(T object) {
		// TODO Auto-generated method stub
			//object=em.merge(object);
			System.out.println("::eliminado el objeto"+object);
			em.remove(em.merge(object));
	}
	@Override
	public T actualizar(T object) {
		// TODO Auto-generated method stub
	//	em.getTransaction().begin();
	return	em.merge(object);
	//	em.getTransaction().commit();
	//	return object;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<T> listar() {
		 List<T> entities = new ArrayList<T>();

	        try {
	            String s =
	                    "select c from " + persistentClass.getSimpleName() + " c";
	            entities = em.createQuery(s).getResultList();
	        } catch (Exception e) {

	           
	        }
	        return entities;

	};
	
	
	@SuppressWarnings("unchecked")
		public GenericSessionImpl() {
		System.out.println("Constructor SessionGenerico persitence Unit es :::"+em+"**********************");
		  this.persistentClass =
              (Class<T>) ((ParameterizedType) getClass()
                  .getGenericSuperclass()).getActualTypeArguments()[0];
	}

}
